# log
# doc https://cuiqingcai.com/6080.html
import logging
import os
import sys
from logging import handlers

from . import cons, config

__all__ = [
    "log"
]

log = logging.root


def _init():
    _log_dir_path = cons.log_dir_path
    os.makedirs(_log_dir_path, mode=0o755, exist_ok=True)

    _format = r'%(asctime)s - %(filename)s[%(lineno)d] - %(levelname)s: %(message)s'

    _formatter = logging.Formatter(_format)
    _time_h = handlers.TimedRotatingFileHandler(
        encoding="utf-8",
        filename=f'{_log_dir_path}/app.log',
        when='D',
        interval=1,
        backupCount=7
    )
    _time_h.setFormatter(_formatter)
    _time_h.suffix = '%y-%m-%d.log'

    _std_h = logging.StreamHandler(stream=sys.stdout)
    _std_h.setFormatter(_formatter)

    global log
    log.setLevel(config.conf.log.level)

    log.addHandler(_time_h)
    log.addHandler(_std_h)


_init()
